package tk.mybatis.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.bimface.sdk.BimfaceClient;
import com.bimface.sdk.bean.request.FileUploadRequest;
import com.bimface.sdk.bean.response.*;
import com.bimface.sdk.exception.BimfaceException;

import tk.mybatis.web.Config;

@Controller
@RequestMapping("BimFace")
public class BimFaceController {
	// 初始化BimfaceClient
	protected static BimfaceClient bimfaceClient = new BimfaceClient(Config.APP_KEY, Config.APP_SECRET);

	//显示上传页面
	@RequestMapping("upload")
	public ModelAndView upload() {
		ModelAndView mv = new ModelAndView("BimFace/upload");
		return mv;
	}

	//上传操作
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public TranslateBean upload(HttpServletRequest request) throws IOException {
		// 上传文件
		FileBean fileBean = null;
		try {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> fileItems = upload.parseRequest(request);
			FileUploadRequest fileUploadRequest = new FileUploadRequest();
			for (FileItem fileItem : fileItems) {
				fileUploadRequest.setContentLength(fileItem.getSize());
				fileUploadRequest.setName(fileItem.getName());
				fileUploadRequest.setInputStream(fileItem.getInputStream());
			}
			fileBean = bimfaceClient.upload(fileUploadRequest);
		} catch (FileUploadException e) {
		} catch (BimfaceException e) {
		}

		// 获取fileId
		Long fileId = fileBean.getFileId();
		// 发起文件转换
		TranslateBean translateBean = null;
		try {
			translateBean = bimfaceClient.translate(fileId);
		} catch (BimfaceException e) {
		}

		return translateBean;
	}
	//显示模型视图
	@RequestMapping(value = "view", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView view(@RequestParam(defaultValue="1239348893253824") String fileId) {
		ModelAndView mv = new ModelAndView("BimFace/view");
		// 获取view token
		String viewToken = null;
		try {
			viewToken = bimfaceClient.getViewTokenByFileId(Long.valueOf(fileId));
		} catch (NumberFormatException e) {
		} catch (BimfaceException e) {
		}
		mv.addObject("viewToken", viewToken);
		return mv;
	}
	//查询文件转换状态
	@RequestMapping(value = "pull", method = RequestMethod.GET)
	@ResponseBody
	public TranslateBean pull(String fileId) {
		// 调用BIMFACE-SDK获取文件转换状态
		TranslateBean translateBean = null;
		try {
			translateBean = bimfaceClient.getTranslate(Long.valueOf(fileId));
		} catch (NumberFormatException e) {
		} catch (BimfaceException e) {
		}
		return translateBean;
	}
}
